package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Test5 {
    public static void main(String[] args) {
        int[] nums1 = new int[]{2, 2, 1, 1, 1, 2, 2};
        int k = majorityElement2(nums1);
        System.out.println(k);
    }

    public static int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.get(nums[i]) == null ? 1 : map.get(nums[i]) + 1);
        }
        Map.Entry<Integer, Integer> majorityEntry = null;
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            if (majorityEntry == null || integerIntegerEntry.getValue() > majorityEntry.getValue()) {
                majorityEntry = integerIntegerEntry;
            }
        }
        return majorityEntry.getKey();
    }

    public static int majorityElement2(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }

    public static int majorityElement3(int[] nums) {
//        Random rand = new Random();
//        rand.nextInt()
        return nums[nums.length / 2];
    }
}
